import React, { useEffect, useLayoutEffect, useState, Fragment } from 'react';
import { eventTrack } from '@/utils/track';
import { connect } from 'umi';
import {
    Form,
    Input,
    Card,
    ConfigProvider,
    Switch,
    Button,
    Checkbox,
    InputNumber,
    Popover,
    Radio
    // Spin
} from 'antd';
import { history } from 'umi';
// import moment from 'moment';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { RadioForm, SelectForm } from '@/components/UserForm';
import { withRoutePage } from '@/utils/enhanceUtils';
import { getTypeList } from '@/services/components/userform';
import OrganizationSelect from '@/components/OrganizationSelect';
import styles from './index.less';

const formItemsLayout = {
    labelCol: {
        md: { span: 4 },
        xs: { span: 12 },
        sm: { span: 12 }
    },
    wrapperCol: {
        md: { span: 12 },
        xs: { span: 12 },
        sm: { span: 12 }
    }
};
const Addholiday = ({
    dispatch,
    form,
    addholiday,
    location,
    loading
    // ...rags
}) => {
    // 获取地址栏的id
    const { id = '', action = '', editleaveCode = '' } = location.query;
    // 获取登陆人公司id
    const user = localStorage.getItem('user');
    const { companyId: userCompanyId } = user ? JSON.parse(user) : {};
    const { getFieldDecorator } = form;
    const { holidayDetail = {} } = addholiday;
    const [isExtendValid, setIsExtendValid] = useState(false);
    const {
        leaveName = '',
        companyCode = userCompanyId,
        leaveNewEmployee = 'after_correction',
        salaryCountType = '1',
        leaveUnit = '2',
        leaveCountType = '1',
        openState = false,
        provideBalanceType = 'manual_opeation',
        extendValid = false,
        extendValidValue = 1,
        extendValidType = '2',
        leaveCode = '',
        leaveNewEmployeeLimitUnit = 'day',
        leaveNewEmployeeLimit = 1,
        attachmentFlag = 0
    } = holidayDetail;
    let disalbedVallue = false;
    if (
        leaveCode === 'CommonYear' ||
        leaveCode === 'CommonSick' ||
        leaveCode === 'CommonPerson' ||
        leaveCode === 'CommonPaid' ||
        leaveCode === 'CommonBaby' ||
        leaveCode === 'SgChild' ||
        leaveCode === 'SgAddChild' ||
        leaveCode === 'CnPater' ||
        leaveCode === 'CnMarry' ||
        leaveCode === 'CnDead' ||
        leaveCode === 'SgMarry' ||
        leaveCode === 'SgAddBaby' ||
        leaveCode === 'SgPater' ||
        leaveCode === 'SgDead' ||
        leaveCode === 'SgUnpaidBaby' ||
        leaveCode === 'SgArmy'
    ) {
        disalbedVallue = true;
    }

    /**
     * 表单提交
     */
    const handleSubmit = e => {
        e.preventDefault();
        form.validateFields((err, values) => {
            // console.log('err', err);
            if (!err) {
                // 转换switch
                let openStateValue = '0';
                if (values.openState === true) {
                    openStateValue = '1';
                }
                // 转换numberinput
                let extendValidCheckbox = '0';
                if (values.extendValid === true) {
                    extendValidCheckbox = '1';
                }
                // 去除父类
                const { Valid, ...newValues } = values;
                // console.log('newValues', newValues);
                // 不启用假期余额 其他字段默认传空
                let payload = {
                    ...values,
                    openState: openStateValue,
                    provideBalanceType: values.openState === true ? values.provideBalanceType : '',
                    extendValid: '',
                    extendValidType: extendValidCheckbox === '0' ? '' : values.extendValidType,
                    extendValidValue: extendValidCheckbox === '0' ? 0 : values.extendValidValue,
                    leaveNewEmployeeLimit: values.leaveNewEmployeeLimit || '',
                    leaveNewEmployeeLimitUnit: values.leaveNewEmployeeLimitUnit || ''
                };
                if (values.Valid) {
                    payload = {
                        ...newValues,
                        openState: openStateValue,
                        provideBalanceType: values.openState === true ? values.provideBalanceType : '',
                        extendValid: extendValidCheckbox,
                        extendValidType: extendValidCheckbox === '0' ? '' : values.extendValidType,
                        extendValidValue: extendValidCheckbox === '0' ? 0 : values.extendValidValue,
                        leaveNewEmployeeLimit: values.leaveNewEmployeeLimit || '',
                        leaveNewEmployeeLimitUnit: values.leaveNewEmployeeLimitUnit || ''
                    };
                }
                if (action === 'edit') {
                    dispatch({
                        type: 'addholiday/editHoliday',
                        payload: {
                            ...payload,
                            id,
                            leaveCode: editleaveCode
                        },
                        success: async () => {
                            // 埋点
                            await eventTrack({
                                eventName: 'personnel_management_attendance_holidayManagement_edit_sumbit_click',
                                eventProps: {
                                    status: 0
                                }
                            });
                            history.push({
                                pathname: '/office/personnelManagement/attendance/holidayManagement'
                            });
                        },
                        err: res => {
                            // 埋点
                            eventTrack({
                                eventName: 'personnel_management_attendance_holidayManagement_edit_sumbit_click',
                                eventProps: {
                                    status: 1,
                                    err_info: res.msg
                                }
                            });
                        }
                    });
                } else {
                    dispatch({
                        type: 'addholiday/addHoliday',
                        payload,
                        success: async () => {
                            // 埋点
                            await eventTrack({
                                eventName: 'personnel_management_attendance_holidayManagement_add_submit_click',
                                eventProps: {
                                    status: 0
                                }
                            });
                            history.push({
                                pathname: '/office/personnelManagement/attendance/holidayManagement'
                            });
                        },
                        err: res => {
                            // 埋点
                            eventTrack({
                                eventName: 'personnel_management_attendance_holidayManagement_add_submit_click',
                                eventProps: {
                                    status: 1,
                                    err_info: res.msg
                                }
                            });
                        }
                    });
                }
            }
        });
    };
    // 编辑假期管理 允许延长有效期余额保留数默认值为0,通过监听isExtendVallid修改默认值为1，
    useLayoutEffect(() => {
        if (isExtendValid) {
            form.setFieldsValue({
                extendValidValue: 1
            });
        }
    }, [isExtendValid]);
    useEffect(() => {
        // 获取假期详情
        if (action === 'edit') {
            dispatch({
                type: 'addholiday/holidayDetail',
                payload: {
                    id
                }
            });
        }
        return () => {
            dispatch({
                type: 'addholiday/save',
                payload: {
                    holidayDetail: {}
                }
            });
        };
    }, []);
    // 三元eslint提出来
    const ifTrue = (
        <Fragment>
            <span
                style={{
                    display: 'inline-block',
                    marginLeft: '5px',
                    float: 'left'
                }}
            >
                ,超过有效期后,余额保留
            </span>
            <Form.Item className={styles.holidayInput}>
                {getFieldDecorator('extendValidValue', {
                    initialValue: extendValidValue,
                    rules: [
                        {
                            required: form.getFieldValue('extendValid'),
                            message: '请输入整数',
                            type: 'number'
                        }
                    ]
                })(
                    <InputNumber
                        min={1}
                        max={form.getFieldValue('extendValidType') === '1' ? 366 : 12}
                        precision={0}
                        style={{
                            display: 'inline-block',
                            marginLeft: '5px',
                            float: 'left',
                            width: '70px'
                        }}
                        onPressEnter={e => {
                            e.preventDefault();
                        }}
                    />
                )}
            </Form.Item>
            {getFieldDecorator('extendValidType', {
                initialValue: extendValidType === '' ? '2' : extendValidType
            })(
                <SelectForm
                    params={{
                        dictCode: 'timeUnitType'
                    }}
                    requireParam={['dictCode']}
                    getData={params =>
                        getTypeList(params).then(res => {
                            if (res && res.code === 10000 && res.data) {
                                return res.data || [];
                            }
                            return [];
                        })
                    }
                    fieldsName={{
                        selectValue: 'dictValue',
                        selectTitle: 'dictName'
                    }}
                    // onChange={this.companyChange}
                    selectProps={{
                        placeholder: '请选择',
                        style: {
                            width: '60px',
                            display: 'inline-block',
                            float: 'left'
                        }
                    }}
                />
            )}
            <span
                style={{
                    display: 'inline-block',
                    color: '#bbb'
                }}
            >
                注：对已设置的延长有效期时间进行修改，要重新对员工批量发放余额或修改员工余额的数据才生效。
            </span>
        </Fragment>
    );
    return (
        <PageHeaderWrapper>
            {/* <Spin spinning={loading}> */}
            <Form layout="horizontal" {...formItemsLayout} onSubmit={handleSubmit}>
                <Card bordered={false} title={action === 'edit' ? '假期设置' : '假期表单'}>
                    <div className="form-Wrap">
                        <ConfigProvider getPopupContainer={trigger => trigger.parentNode}>
                            {/* <Form layout="horizontal" {...formItemLayout}> */}
                            {/* <div className="vv-from-title">假期表单</div> */}
                            <div className="form-Wrap">
                                {/* <FormContainer> */}
                                <Form.Item label="假期名称">
                                    {getFieldDecorator('leaveName', {
                                        initialValue: leaveName,
                                        rules: [
                                            {
                                                required: true,
                                                message: '请输入假期名称2-50字符',
                                                min: 2,
                                                max: 50
                                            }
                                        ]
                                    })(
                                        <Input
                                            disabled={disalbedVallue}
                                            onPressEnter={e => {
                                                e.preventDefault();
                                            }}
                                        />
                                    )}
                                </Form.Item>
                                <Form.Item label="适用范围">
                                    {getFieldDecorator('companyCode', {
                                        initialValue: companyCode
                                    })(<OrganizationSelect isStrictly maxTagCount={2} isNeedPermission />)}
                                </Form.Item>
                                <Form.Item label="新员工请假">
                                    {getFieldDecorator('leaveNewEmployee', {
                                        initialValue: leaveNewEmployee,
                                        rules: [
                                            {
                                                validator: (rule, value, callback) => {
                                                    if (value === 'after_entry_limit') {
                                                        if (!form.getFieldValue('leaveNewEmployeeLimit')) {
                                                            callback('仅支持输入1-999的整数！');
                                                        } else if (!form.getFieldValue('leaveNewEmployeeLimitUnit')) {
                                                            callback('请选择单位！');
                                                        } else {
                                                            callback();
                                                        }
                                                    } else {
                                                        callback();
                                                    }
                                                }
                                            }
                                        ]
                                    })(
                                        <RadioForm
                                            form={form}
                                            params={{
                                                dictCode: 'newEmployeeLeave'
                                            }}
                                            requireParam={['dictCode']}
                                            getData={params =>
                                                getTypeList(params).then(res => {
                                                    if (res && res.code === 10000 && res.data) {
                                                        return res.data || [];
                                                    }
                                                    return [];
                                                })
                                            }
                                            filterItem="无要求"
                                            fieldsName={{
                                                radioValue: 'dictValue',
                                                radioTitle: 'dictName'
                                            }}
                                            // onChange={this.companyChange}
                                            radioProps={{
                                                placeholder: '请选择'
                                            }}
                                            inputProps={{
                                                leaveNewEmployeeLimit,
                                                leaveNewEmployeeLimitUnit,
                                                disabled: disalbedVallue
                                            }}
                                        />
                                    )}
                                </Form.Item>
                                <Form.Item label="是否带薪">
                                    {getFieldDecorator('salaryCountType', {
                                        initialValue: salaryCountType
                                    })(
                                        <RadioForm
                                            params={{
                                                dictCode: 'salaryCountType'
                                            }}
                                            requireParam={['dictCode']}
                                            getData={params =>
                                                getTypeList(params).then(res => {
                                                    if (res && res.code === 10000 && res.data) {
                                                        return res.data || [];
                                                    }
                                                    return [];
                                                })
                                            }
                                            filterItem="无要求"
                                            fieldsName={{
                                                radioValue: 'dictValue',
                                                radioTitle: 'dictName'
                                            }}
                                            // onChange={this.companyChange}
                                            radioProps={{
                                                placeholder: '请选择'
                                            }}
                                        />
                                    )}
                                </Form.Item>
                                <Form.Item label="附件是否必传">
                                    {getFieldDecorator('attachmentFlag', {
                                        initialValue: attachmentFlag
                                    })(
                                        <Radio.Group>
                                            <Radio value={0}>否</Radio>
                                            <Radio value={1}>是</Radio>
                                        </Radio.Group>
                                    )}
                                </Form.Item>
                                <Form.Item label="最小请假单位">
                                    {getFieldDecorator('leaveUnit', {
                                        initialValue: companyCode === 101 && action !== 'edit' ? '1' : leaveUnit
                                    })(
                                        <SelectForm
                                            params={{
                                                dictCode: 'leaveUnitType'
                                            }}
                                            requireParam={['dictCode']}
                                            getData={params =>
                                                getTypeList(params).then(res => {
                                                    if (res && res.code === 10000 && res.data) {
                                                        return res.data || [];
                                                    }
                                                    return [];
                                                })
                                            }
                                            fieldsName={{
                                                selectValue: 'dictValue',
                                                selectTitle: 'dictName'
                                            }}
                                            // onChange={this.companyChange}
                                            selectProps={{
                                                placeholder: '请选择应聘职位'
                                            }}
                                        />
                                    )}
                                </Form.Item>
                                <Form.Item label="请假时长核算">
                                    {getFieldDecorator('leaveCountType', {
                                        initialValue: leaveCountType
                                    })(
                                        <SelectForm
                                            params={{
                                                dictCode: 'leaveCountType'
                                            }}
                                            requireParam={['dictCode']}
                                            getData={params =>
                                                getTypeList(params).then(res => {
                                                    if (res && res.code === 10000 && res.data) {
                                                        return res.data || [];
                                                    }
                                                    return [];
                                                })
                                            }
                                            fieldsName={{
                                                selectValue: 'dictValue',
                                                selectTitle: 'dictName'
                                            }}
                                            // onChange={this.companyChange}
                                            selectProps={{
                                                placeholder: '请选择应聘职位'
                                            }}
                                        />
                                    )}
                                </Form.Item>
                                {/* </FormContainer> */}
                                <Form.Item label="启用假期余额">
                                    {getFieldDecorator('openState', {
                                        valuePropName: 'checked',
                                        initialValue: openState === '1'
                                    })(<Switch checkedChildren="开" unCheckedChildren="关" />)}
                                    <Popover
                                        title="启用假期余额说明："
                                        trigger="click"
                                        placement="topLeft"
                                        content={
                                            <div style={{ width: '630px' }}>
                                                <p>
                                                    关闭开关：假期余额不限制，申请此假期不受余额限制，员工请假时不显示此类假期余额；
                                                </p>
                                                <p>启动开关：启用假期余额，申请此假期受余额限制；</p>
                                                <p>
                                                    ①启动假期余额但没有对员工假期余额赋值，此时假期余额默认为0，员工请假受限，提示余额不足。
                                                </p>
                                                <p>
                                                    ②启动假期余额且对员工假期余额赋值，此时有假期余额为赋值数，员工请假会提示当前可用余额。
                                                </p>
                                                <p>③“员工假期余额”的批量发放和修改假期余额只支持启用后的假期类型</p>
                                            </div>
                                        }
                                    >
                                        <a href="#" style={{ marginLeft: '5px' }}>
                                            使用说明
                                        </a>
                                    </Popover>
                                </Form.Item>
                                {form.getFieldValue('openState') === true ? (
                                    <span>
                                        <Form.Item label="余额发放方式" {...formItemsLayout}>
                                            {getFieldDecorator('provideBalanceType', {
                                                initialValue:
                                                    provideBalanceType === '' ? 'manual_opeation' : provideBalanceType
                                            })(
                                                <SelectForm
                                                    params={{
                                                        dictCode: 'provideBalanceType'
                                                    }}
                                                    requireParam={['dictCode']}
                                                    getData={params =>
                                                        getTypeList(params).then(res => {
                                                            if (res && res.code === 10000 && res.data) {
                                                                return res.data || [];
                                                            }
                                                            return [];
                                                        })
                                                    }
                                                    fieldsName={{
                                                        selectValue: 'dictValue',
                                                        selectTitle: 'dictName'
                                                    }}
                                                    // onChange={this.companyChange}
                                                    selectProps={{
                                                        placeholder: '请选择'
                                                    }}
                                                />
                                            )}
                                        </Form.Item>
                                        <Form.Item
                                            label="假期余额有效期"
                                            // {...formItemrLayout}
                                            className={styles.timeVality}
                                        >
                                            {getFieldDecorator('Valid', {
                                                initialValue: {
                                                    extendValid,
                                                    extendValidValue,
                                                    extendValidType
                                                }
                                            })(
                                                <Fragment>
                                                    <span
                                                        style={{
                                                            display: 'block'
                                                        }}
                                                    >
                                                        按自然月（1月1日-12月31日）
                                                    </span>
                                                    {getFieldDecorator('extendValid', {
                                                        valuePropName: 'checked',
                                                        initialValue: extendValid === '1'
                                                    })(
                                                        <Checkbox
                                                            // checked={
                                                            //     extendValid
                                                            // }
                                                            style={{
                                                                float: 'left'
                                                            }}
                                                            onChange={checkedValue => {
                                                                if (
                                                                    checkedValue.target.checked === true &&
                                                                    extendValidValue === 0
                                                                ) {
                                                                    setIsExtendValid(true);
                                                                }
                                                            }}
                                                        >
                                                            允许延长有效期
                                                        </Checkbox>
                                                    )}

                                                    {form.getFieldValue('extendValid') === true ? ifTrue : ''}
                                                </Fragment>
                                            )}
                                        </Form.Item>
                                    </span>
                                ) : null}

                                <Form.Item label className={styles.subbutton}>
                                    <Button
                                        type="primary"
                                        htmlType="submit"
                                        loading={
                                            loading.effects['addholiday/editHoliday'] ||
                                            loading.effects['addholiday/addHoliday']
                                        }
                                    >
                                        提交
                                    </Button>
                                    <Button
                                        type="button"
                                        style={{ marginLeft: '5px' }}
                                        onClick={async () => {
                                            // 埋点
                                            await eventTrack({
                                                eventName:
                                                    'personnel_management_attendance_holidayManagement_add_cancel_click'
                                            });
                                            history.push({
                                                pathname: '/office/personnelManagement/attendance/holidayManagement'
                                            });
                                        }}
                                    >
                                        取消
                                    </Button>
                                </Form.Item>
                            </div>
                            {/* </Form> */}
                        </ConfigProvider>
                    </div>
                </Card>
            </Form>
            {/* </Spin> */}
        </PageHeaderWrapper>
    );
};
export default withRoutePage(
    connect(({ loading, addholiday }) => ({
        loading,
        addholiday
    }))(Form.create()(Addholiday))
);
